﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace _1._2._3_基于_HttpListener_的_Web_服务器
{
    public class SimpleHttpListener//区别net自带的类，小写：呵呵呵呵
    {
        public void Run()
        {
            //TcpListener方式在进化，简单编码

            if (!HttpListener.IsSupported)
            {
                throw new InvalidOperationException(
                    "win xp sp2或者server 2003以上！"
                    );
            }
                string[] prefixs = new string[] { "http://127.0.0.1:2451/" };
                HttpListener listener = new HttpListener();
                foreach (string item in prefixs)
                {
                    listener.Prefixes.Add(item);
                }
                listener.Start();
                Console.WriteLine("监听中...");
                while (true)
                {
                    HttpListenerContext context = listener.GetContext();
                    HttpListenerRequest request = context.Request;
                    Console.WriteLine("{0} {1} HTTP/1.1", request.HttpMethod, request.RawUrl);
                   // Console.WriteLine("Accept: {0} ", string.Join(",", request.AcceptTypes));
                    Console.WriteLine("Accept-Language: {0}", string.Join(",", request.UserLanguages));
                    Console.WriteLine("Connection: {0}", request.KeepAlive ? "Keep-Alive" : "close");
                    Console.WriteLine("Host: {0}", request.UserHostName);
                    Console.WriteLine("Pragma: {0}", request.Headers["Pragma"]);
                    HttpListenerResponse response = context.Response;
                    Encoding utf8 = Encoding.UTF8;
                    string responseString = @"<html>
                            <head><title>来自Socket服务器</title></head>
                            <body><h1>你猜中了么</h1></body>
                        </html>";
                    response.ContentLength64 = utf8.GetByteCount(responseString);
                    response.ContentType = "txt/html;charset=utf-8";
                    Stream outputstream = response.OutputStream;
                    StreamWriter client = new StreamWriter(outputstream);
                    client.Write(responseString);
                    client.Close();
                    if (Console.KeyAvailable)
                    {
                        break;
                    }
                    
                    

                }
                listener.Stop();
            }
        }
    }

